package com.lw.servicebase.shiro;


import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;


public class SessionManager extends DefaultWebSessionManager {
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        //当登陆时获取请求头token中的数据
        String id= WebUtils.toHttp( request ).getHeader( "Authorization" );
        if (StringUtils.isEmpty( id )){
            //如果没有携带,生成新的sessionId
            return super.getSessionId( request,response );
        }else {
            //检查sessionId
            request.setAttribute( ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,"header" );
            request.setAttribute( ShiroHttpServletRequest.REFERENCED_SESSION_ID,id );
            request.setAttribute( ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID,Boolean.TRUE);
            //返回sessionId
            return id;
        }
    }
}
